package me.cxlr.qinlauncher2.view.settings;

import android.os.Bundle;

import androidx.appcompat.app.AlertDialog;
import androidx.preference.DropDownPreference;
import androidx.preference.ListPreference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.SwitchPreferenceCompat;

import java.util.ArrayList;
import java.util.List;

import me.cxlr.qinlauncher2.R;
import me.cxlr.qinlauncher2.constants.Constants;
import me.cxlr.qinlauncher2.constants.LauncherAction;
import me.cxlr.qinlauncher2.dao.ActionDao;
import me.cxlr.qinlauncher2.dao.AppDao;
import me.cxlr.qinlauncher2.dao.DockActionDao;
import me.cxlr.qinlauncher2.model.Action;
import me.cxlr.qinlauncher2.model.App;
import me.cxlr.qinlauncher2.model.AppAndAction;
import me.cxlr.qinlauncher2.model.DockAction;
import me.cxlr.qinlauncher2.util.ResourceUtil;
import me.cxlr.qinlauncher2.util.SharedPreferencesUtil;
import me.cxlr.qinlauncher2.util.ThemeUtil;

/**
 * @author 酷安用户:山轮纸
 */
public class DockSettingsFragment extends PreferenceFragmentCompat {
    private AppDao appDao;
    private ActionDao actionDao;
    private DockActionDao dockActionDao;

    private SwitchPreferenceCompat useDock;
    private ListPreference dockIcons;
    private ListPreference dockIconSize;
    private DropDownPreference dockIcon1;
    private DropDownPreference dockIcon2;
    private DropDownPreference dockIcon3;
    private DropDownPreference dockIcon4;
    private DropDownPreference dockIcon5;

    private String iconNumber;
    private boolean useDockFlag;

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.preferences_dock_settings, rootKey);

        appDao = new AppDao();
        actionDao = new ActionDao();
        dockActionDao = new DockActionDao();

        useDock = findPreference("use_dock");
        dockIcons = findPreference("dock_icons");
        dockIconSize = findPreference("dock_icon_size");
        dockIcon1 = findPreference("dock_icon_1");
        dockIcon2 = findPreference("dock_icon_2");
        dockIcon3 = findPreference("dock_icon_3");
        dockIcon4 = findPreference("dock_icon_4");
        dockIcon5 = findPreference("dock_icon_5");

        useDockFlag = SharedPreferencesUtil.getInstance().getBoolean("use_dock", true);
        useDock(useDockFlag);
        useDock.setOnPreferenceChangeListener(((preference, newValue) -> {
            useDockFlag = Boolean.parseBoolean(newValue.toString());
            useDock(useDockFlag);
            return true;
        }));

        iconNumber = SharedPreferencesUtil.getInstance().getString("dock_icons", "3");
        loadIconSelect(iconNumber);
        dockIcons.setOnPreferenceChangeListener((preference, newValue) -> {
            iconNumber = newValue.toString();
            loadIconSelect(iconNumber);
            return true;
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        ThemeUtil.initTheme();
    }

    private void useDock(boolean useDockFlag) {
        if (useDockFlag) {
            dockIcons.setEnabled(true);
            dockIconSize.setEnabled(true);
            dockIcon1.setEnabled(true);
            dockIcon2.setEnabled(true);
            dockIcon3.setEnabled(true);
            dockIcon4.setEnabled(true);
            dockIcon5.setEnabled(true);
        } else {
            dockIcons.setEnabled(false);
            dockIconSize.setEnabled(false);
            dockIcon1.setEnabled(false);
            dockIcon2.setEnabled(false);
            dockIcon3.setEnabled(false);
            dockIcon4.setEnabled(false);
            dockIcon5.setEnabled(false);
        }
    }

    private void loadIconSelect(String number) {
        DockAction dockAction1;
        DockAction dockAction2;
        DockAction dockAction3;
        DockAction dockAction4;
        DockAction dockAction5;

        switch (number) {
            case "3":
                dockAction1 = dockActionDao.findDockActionByIconNumberAndIconName(3, "icon1");
                setSummary(dockAction1, dockIcon1);
                dockIcon1.setOnPreferenceClickListener(preference -> {
                    dialogChoice("选择图标1", dockAction1, dockIcon1);
                    return true;
                });
                dockAction2 = dockActionDao.findDockActionByIconNumberAndIconName(3, "icon2");
                setSummary(dockAction2, dockIcon2);
                dockIcon2.setOnPreferenceClickListener(preference -> {
                    dialogChoice("选择图标2", dockAction2, dockIcon2);
                    return true;
                });
                dockAction3 = dockActionDao.findDockActionByIconNumberAndIconName(3, "icon3");
                setSummary(dockAction3, dockIcon3);
                dockIcon3.setOnPreferenceClickListener(preference -> {
                    dialogChoice("选择图标3", dockAction3, dockIcon3);
                    return true;
                });
                dockIcon4.setVisible(false);
                dockIcon5.setVisible(false);
                break;
            case "5":
                dockAction1 = dockActionDao.findDockActionByIconNumberAndIconName(5, "icon1");
                setSummary(dockAction1, dockIcon1);
                dockIcon1.setOnPreferenceClickListener(preference -> {
                    dialogChoice("选择图标1", dockAction1, dockIcon1);
                    return true;
                });
                dockAction2 = dockActionDao.findDockActionByIconNumberAndIconName(5, "icon2");
                setSummary(dockAction2, dockIcon2);
                dockIcon2.setOnPreferenceClickListener(preference -> {
                    dialogChoice("选择图标2", dockAction2, dockIcon2);
                    return true;
                });
                dockAction3 = dockActionDao.findDockActionByIconNumberAndIconName(5, "icon3");
                setSummary(dockAction3, dockIcon3);
                dockIcon3.setOnPreferenceClickListener(preference -> {
                    dialogChoice("选择图标3", dockAction3, dockIcon3);
                    return true;
                });
                dockAction4 = dockActionDao.findDockActionByIconNumberAndIconName(5, "icon4");
                dockIcon4.setVisible(true);
                setSummary(dockAction4, dockIcon4);
                dockIcon4.setOnPreferenceClickListener(preference -> {
                    dialogChoice("选择图标4", dockAction4, dockIcon4);
                    return true;
                });
                dockAction5 = dockActionDao.findDockActionByIconNumberAndIconName(5, "icon5");
                dockIcon5.setVisible(true);
                setSummary(dockAction5, dockIcon5);
                dockIcon5.setOnPreferenceClickListener(preference -> {
                    dialogChoice("选择图标5", dockAction5, dockIcon5);
                    return true;
                });
                break;
            default:
                break;
        }
    }

    /**
     * 选择动作或应用
     *
     * @param title title
     */
    private void dialogChoice(String title, DockAction dockAction, DropDownPreference dropDownPreference) {
        ArrayList<AppAndAction> appAndActionList = new ArrayList<>(16);
        List<Action> actionList = actionDao.findAllAction();
        if (actionList != null) {
            for (Action entity : actionList) {
                String label = ResourceUtil.getString(requireActivity(), entity.getResLabel());
                if (entity.getActionName().equals(LauncherAction.NO.getAction())) {
                    appAndActionList.add(AppAndAction.builder().id(entity.getId()).label(label).type(0).build());
                } else if (entity.getActionName().equals(LauncherAction.APP_DRAWER.getAction())) {
                    appAndActionList.add(AppAndAction.builder().id(entity.getId()).label(label).type(2).build());
                }
            }
        }
        List<App> appList = appDao.findAllApp();
        if (appList != null) {
            for (App entity : appList) {
                appAndActionList.add(AppAndAction.builder().id(entity.getId()).label(entity.getLabel()).type(1).build());
            }
        }

        String[] id = new String[appAndActionList.size()];
        String[] label = new String[appAndActionList.size()];
        int[] type = new int[appAndActionList.size()];
        for (int i = 0; i < appAndActionList.size(); i++) {
            id[i] = appAndActionList.get(i).getId();
            label[i] = appAndActionList.get(i).getLabel();
            type[i] = appAndActionList.get(i).getType();
        }

        AlertDialog alertDialog = new AlertDialog.Builder(requireContext())
                .setTitle(title)
                .setItems(label, (dialog, which) -> {
                    updateDockAction(dockAction, dropDownPreference, id[which], type[which]);
                    dialog.dismiss();
                })
                .setPositiveButton("关闭", (dialog, which) -> dialog.dismiss())
                .create();
        alertDialog.show();
    }

    /**
     * 修改托盘对应的动作
     *
     * @param dockAction         托盘动作
     * @param dropDownPreference DropDownPreference
     * @param id                 被选中的Id
     * @param type               被选中的Id的类型
     */
    private void updateDockAction(DockAction dockAction, DropDownPreference dropDownPreference, String id, int type) {
        if (type == Constants.KEY_ACTION_TYPE_OPEN_APP) {
            App app = appDao.findAppById(id);
            dockAction.setActionType(1);
            dockAction.setAction(null);
            dockAction.setApp(app);
        } else if (type == Constants.KEY_ACTION_TYPE_ACTION) {
            Action action = actionDao.findActionById(id);
            dockAction.setActionType(2);
            dockAction.setAction(action);
            dockAction.setApp(null);
        } else if (type == Constants.KEY_ACTION_TYPE_NO) {
            dockAction.setActionType(0);
            dockAction.setAction(null);
            dockAction.setApp(null);
        }
        dockActionDao.updateDockAction(dockAction);
        setSummary(dockAction, dropDownPreference);
    }

    /**
     * 设置提示
     *
     * @param dockAction         托盘动作
     * @param dropDownPreference DropDownPreference
     */
    private void setSummary(DockAction dockAction, DropDownPreference dropDownPreference) {
        switch (dockAction.getActionType()) {
            case 1:
                dropDownPreference.setSummary(getString(R.string.number_key_select_open_app_summary, dockAction.getApp().getLabel()));
                break;
            case 2:
                String label = ResourceUtil.getString(requireActivity(), dockAction.getAction().getResLabel());
                dropDownPreference.setSummary(getString(R.string.number_key_select_action_summary, label));
                break;
            case 0:
                dropDownPreference.setSummary(getString(R.string.dock_summary_select_no));
                break;
            default:
                break;
        }
    }

}